package com.esyoga.yoyoga.handler;
import com.esyoga.yoyoga.enums.UserTypeEn;
import com.esyoga.yoyoga.pojo.TTrainer;
import com.esyoga.yoyoga.service.TrainerVerifyService;
import com.esyoga.yoyoga.util.EncryptionUtil;
import com.esyoga.yoyoga.util.UsernamePasswordByUserTypeToken;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Data
@Controller
@RequestMapping("/trainerVerify")
public class TrainerVerifyHandler {
    @Resource
    private TrainerVerifyService trainerVerifyService;

    @RequestMapping("/userRegisterByPhone")
    @ResponseBody
    public String trainerRegisterByPhone(String tPassword, String code, HttpServletRequest request) {

        if (tPassword == null || code == null) {
            return null;
        }
        String state = "操作失败";
        HttpSession session = request.getSession();
        String oldCode = (String) session.getAttribute("registerCode");
        String phone = (String) session.getAttribute("phoneNumber");
        if (code.equals(oldCode)) {
            //验证码验证通过
            String password = trainerVerifyService.findTrainerPasswordByPhone(phone);
            //判断是否手机号已存在
            if (password != null) {
                //查询到密码
                state = "手机号已存在";
            } else {
                //密码加密
                String md5Pwd = EncryptionUtil.encryptionPwd(tPassword, phone);
                //插入用户数据
                int i = trainerVerifyService.trainerRegister(phone, md5Pwd);
                if (i > 0) {
                    state = "注册成功";
                }
            }

        } else {
            state = "验证码不正确";
        }
        System.out.println("状态：" + state);
        session.removeAttribute("registerCode");
        session.removeAttribute("phoneNumber");
        return state;
    }

    /**
     * 后台直接注册教练信息
     *
     * @param phone
     * @param tpassword
     * @return
     */
    @RequestMapping("/insertTrainerInfo")
    @ResponseBody
    public Map<String,Object> insertTrainerInfo(String tpassword, String phone) {
        if (phone == null || tpassword == null) {
            return null;
        }
        String state = "操作失败";
        Map<String,Object> map = new HashMap<>();
        String pwd = trainerVerifyService.findTrainerPasswordByPhone(phone);
        //判断是否手机号已存在
        if (pwd != null) {
            //查询到密码
            state = "手机号已存在";
        } else {

            //密码加密
            String md5Pwd = EncryptionUtil.encryptionPwd(tpassword, phone);
            //插入用户数据
            int i = trainerVerifyService.trainerRegister(phone, md5Pwd);
            if (i > 0) {
                state = "注册成功";
            }
        }

        System.out.println("状态：" + state);
        map.put("state", state);
        return map;
    }

    /**
     * 教练验证码登录
     *
     * @param phoneNumber
     * @param code
     * @param UserType
     * @param request
     * @return
     */
    @RequestMapping("/gymLoginByCode")
    @ResponseBody
    public Map<String,Object> gymLoginByCode(String phoneNumber, String code, int UserType, HttpServletRequest request) {
        if (phoneNumber == null || code == null) {
            return null;
        }
        //获取subject对象
        Subject currentUser = SecurityUtils.getSubject();
        Map<String,Object> map = new HashMap<>();
        map.put("msg","您已登录，切勿重复登录");
        //如果验证过了就直接跳过
        if (!currentUser.isAuthenticated()) {
            HttpSession httpSession = request.getSession();
            Session currentUserSession = currentUser.getSession();
            //获取session中的验证码中的账号
            String loginPhoneNumber = (String) httpSession.getAttribute("loginPhoneNumber");
            String sessionCode = (String) httpSession.getAttribute("loginCode");
            //通过账号查密码
            String Password = trainerVerifyService.findTrainerPasswordByPhone(phoneNumber);
            //获取session
            if (!code.equals(sessionCode) || !loginPhoneNumber.equals(phoneNumber)) {
                //验证码或者账号不匹配
                map.put("success", false);
                map.put("msg", "验证码有误");
                return map;
            } else if (Password == null) {
                map.put("success", false);
                map.put("msg", "用户名不存在，请选先注册");
                return map;
            }
            UsernamePasswordByUserTypeToken token = new UsernamePasswordByUserTypeToken(phoneNumber, Password, UserType);

            try {
                //将用户类型、姓名存储到subject session中
                currentUserSession.setAttribute("phoneNumber", phoneNumber);
                currentUserSession.setAttribute("userType", UserType);
                currentUser.login(token);
                TTrainer tTrainer = trainerVerifyService.findTrainerByPhone(phoneNumber);
                //存入用户类型和pojo到session
                httpSession.setAttribute("userType", UserType);
                httpSession.setAttribute("tTrainer", tTrainer);
                httpSession.setAttribute("userTypeEn", UserTypeEn.TRAINER);
                httpSession.setAttribute("user", tTrainer);
                System.out.println("登录成功");
                map.put("msg", "登陆成功");
                if(tTrainer.gettName()!=null){
                    //如果是老用户
                    map.put("state",1);
                }else{
                    //新用户
                    map.put("state",0);
                }
                return map;
            } catch (UnknownAccountException e) {
                System.out.println("用户不存在");
                map.put("success", false);
                map.put("msg", "用户不存在");
            } catch (IncorrectCredentialsException e) {
                System.out.println("密码不对");
                map.put("success", false);
                map.put("msg", "密码不正确");
            } catch (LockedAccountException e) {
                System.out.println("账户被锁定");
                map.put("success", false);
                map.put("msg", "账号被锁定");

            } catch (Exception e) {
                System.out.println("其他异常");
                map.put("success", false);
                map.put("msg", "其他异常");
            }

        }
        return map;
    }

    /**
     * 教练账号密码登录
     *
     * @param phoneNumber
     * @param sPassword
     * @param rm
     * @param UserType
     * @return
     */
    @RequestMapping("/trainerLoginByPhone")
    @ResponseBody
    public Map<String,Object> trainerLoginByPhone(String phoneNumber, String sPassword, String rm, int UserType, HttpServletRequest request) {
        System.out.println("教练传入信息："+phoneNumber+":"+sPassword+":"+rm+":"+UserType);
        if (phoneNumber == null || sPassword == null) {
            return null;
        }
        //获取subject对象
        Subject currentUser = SecurityUtils.getSubject();
        Map<String,Object> map = new HashMap<>();
        map.put("msg","您已登录，切勿重复登录");
        //如果验证过了就直接跳过
        if (!currentUser.isAuthenticated()) {
            HttpSession httpSession = request.getSession();
            Session currentUserSession = currentUser.getSession();
            // 加密输入的账号进行匹配
            String md5Pwd = EncryptionUtil.encryptionPwd(sPassword, phoneNumber);
            UsernamePasswordByUserTypeToken token = new UsernamePasswordByUserTypeToken(phoneNumber, md5Pwd, UserType);
            if (rm.equals("on")) {
                // 设置记住我
                System.out.println("记住我");
                token.setRememberMe(true);
            }
            try {
                //将用户类型、姓名存储到session中
                currentUserSession.setAttribute("phoneNumber", phoneNumber);
                currentUserSession.setAttribute("userType", UserType);
                currentUser.login(token);
                TTrainer tTrainer = trainerVerifyService.findTrainerByPhone(phoneNumber);
                //存入用户类型和pojo到session
                httpSession.setAttribute("userType", UserType);
                httpSession.setAttribute("tTrainer", tTrainer);
                httpSession.setAttribute("userTypeEn", UserTypeEn.TRAINER);
                httpSession.setAttribute("user", tTrainer);
                System.out.println("登录成功");
                map.put("msg", "登陆成功");
                if(tTrainer.gettName()!=null){
                    //如果是老用户
                    map.put("state",1);
                }else{
                    //新用户
                    map.put("state",0);
                }
                return map;
            } catch (UnknownAccountException e) {
                System.out.println("用户不存在");
                map.put("success", false);
                map.put("msg", "用户不存在");
            } catch (IncorrectCredentialsException e) {
                System.out.println("密码不对");
                map.put("success", false);
                map.put("msg", "密码不正确");
            } catch (LockedAccountException e) {
                System.out.println("账户被锁定");
                map.put("success", false);
                map.put("msg", "账号被锁定");

            } catch (Exception e) {
                System.out.println("其他异常");
                map.put("success", false);
                map.put("msg", "其他异常");
            }

        }
        return map;
    }

    /**
     * 完善教练用户信息
     * @param tTrainer
     * @return
     */
    @RequestMapping("/trainerAddInfo")
    @ResponseBody
    public String trainerAddInfo(TTrainer tTrainer,HttpServletRequest request){
        System.out.println("trainer:"+tTrainer.toString());
        if(tTrainer==null){
            return null;
        }
        String state = "更新失败";

        HttpSession httpSession = request.getSession();
        Object object = httpSession.getAttribute("tTrainer");
        if(object==null){
            state = "登录信息已失效，请重新登录";
            return state;
        }
        //获取session中的tstudent,将账号赋给传入的student
        TTrainer sessionTTrainer = (TTrainer)object;
        String account = sessionTTrainer.gettAccount();
        tTrainer.settAccount(account);
        int i = trainerVerifyService.trainerAddInfo(tTrainer);
        if(i>0){
            state = "更新成功";
        }
        return state;
    }

    /**
     * 教练重置密码请求
     * @param restPhone
     * @param restPassword
     * @param code
     * @param request
     * @return
     */
    @RequestMapping("/trainerRestPassword")
    @ResponseBody
    public String studentRestPassword(String restPhone,String restPassword,String code,HttpServletRequest request){
        System.out.println(restPhone+":"+restPassword);
        if(restPhone==null || restPassword==null|| code==null){
            return null;
        }
        String state = "操作失败";
        HttpSession session = request.getSession();
        String oldCode = (String) session.getAttribute("restCode");
        String  restPhoneNumber =(String)session.getAttribute("restPhoneNumber");
        if(code.equals(oldCode)&&(restPhone.equals(restPhoneNumber))){
            //验证码验证通过
            String password = trainerVerifyService.findTrainerPasswordByPhone(restPhone);
            //判断是否手机号已存在
            if(password!=null){
                //查询到密码-用户存在，执行重置密码
                String md5Pwd = EncryptionUtil.encryptionPwd(restPassword, restPhone);
                int i = trainerVerifyService.resetPassword(restPhone, md5Pwd);
                if(i>0){
                    state = "重置成功";
                }
            }else{
                state = "用户不存在";
            }

        }else {
            state = "验证码不正确";
        }
        System.out.println("状态："+state);
        session.removeAttribute("restCode");
        return state;
    }

    /**
     * 获取session中的值
     * @param request
     * @return
     */
    @RequestMapping("/getTrainerValue")
    @ResponseBody
    public Map<String,Object> getTrainerValue(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>(1);
        TTrainer tTrainer = (TTrainer) request.getSession().getAttribute("tTrainer");
        map.put("tTrainer",tTrainer);
        return map;
    }
}
